import '../sass/list.scss'


/****************  +++导航登录 ******************/
const list_login_off = document.querySelector('.list_login_off')
const login_login_on = document.querySelector('.login_login_on > p')
const login_login_onApp = document.querySelector('.login_login_on')
const idnav = window.localStorage.getItem('id')
const tokennav = window.localStorage.getItem('token')


$.ajax({
    url:'http://localhost:8888/users/info?id='+idnav,
    headers:{ authorization: 'tokennav'},
    success(res){
        console.log(res)

        if(res.code === 1){
            login_login_on.innerText = res.info.nickname
            login_login_onApp.style.display = 'block'
            list_login_off.style.display = 'none'
        }
    }
})

$('.login_login_on').on('mouseover', () => {
    $('.login_login_on > ol').stop().slideDown()
})
$('.login_login_on').on('mouseout', () => {
    $('.login_login_on > ol').stop().slideUp()
})

/****************  +++导航结束 ******************/


/****************  +++导航退出登录 ******************/
$('.logout').on('click', () => {
    
    $.ajax({
        url: 'http://localhost:8888/users/logout?id='+idnav,
        success(res){
            if (res.code === 1) {
                window.localStorage.removeItem('id')
                window.localStorage.removeItem('token')
                window.location.reload()
              }
        }
    })
})









const listTabs = document.querySelector('.list_bottom > li')
const list_choose = document.querySelector('.list_choose >.rig')
const list_sale = document.querySelector('.list_sale > .rig ')
const list_sort = document.querySelector('.list_sort > .rig ')
const listClass = document.querySelector('.list_top > .list_class > .rig ')
const listClass_ = document.querySelector('.list_top > .list_class > .rig > li')
const list_bottom = document.querySelector('.list_bottom')
const pagelef = document.querySelector('.pagelef')
const Page_total = document.querySelector('.Page_total')
const pagerig = document.querySelector('.pagerig')
const list_pigeSize = document.querySelector('.list_pigeSize')
const choose_page = document.querySelector('.choose_page > input')
const goToPage = document.querySelector('goToPage')
const list_top = document.querySelector('.list_top')
const list_search_inp = document.querySelector('.list_search_inp')



/****************  +++渲染页面分类 ******************/
goodsClass()

async function goodsClass() {
    const res = await $.ajax({
        url: 'http://localhost:8888/goods/category'
    })

    let str = `
    <li class="cate active">全部</li>
    `

    res.list.forEach(item => {
        str += `
        <li class="cate">${item}</li>
        `
    })
    listClass.innerHTML = str
}
/****************  分类渲染完毕 ******************/

/****************  +++页面渲染 ******************/

const listInfo = {
    current: 1,
    pagesize: 24,
    search: '',
    filter: '',
    saleType: 10,
    sortType: 'id',
    sortMethod: 'ASC',
    category: ''
}
goodsList()
async function goodsList() {
    const res = await $.ajax({
        url: 'http://localhost:8888/goods/list',
        data: listInfo
    })
    console.log(res)
    let str = ` `

    res.list.forEach(item => {
        str += `              
        <li data-id="${item.goods_id}">
        <img width=270 height=270 data-src="${item.img_big_logo}" alt="" class="goods_img">
        ${item.is_sale ? '<span class="SALE">SALE</span>' : ''}
        ${item.is_hot ? '<span class="HOT">HOT</span>' : ''}
       
        <p class="jieshao">
         ${item.title}
        </p>
        <p class="price">
              <span class="new">￥${item.current_price}</span>
              <span class="old">￥${item.price}</span>
        </p>
        <button data-id="${item.goods_id}">加入购物车</button>
        </li>
        `
    })
    list_bottom.innerHTML = str
    /****************  渲染分页器 ******************/
    pagelef.className = listInfo.current === 1 ? 'pagelef active' : 'pagelef'
    pagerig.className = listInfo.current === res.total ? 'pagerig active' : 'pagerig'
    Page_total.innerText = listInfo.current + ' / ' + res.total
    list_pigeSize.value = listInfo.pagesize
    choose_page.value = listInfo.current
    choose_page.dataset.total = res.total  // 用于判断跳转是否大于最大页数

    useLazyList()
}
/*************** LazyLoad *****************/
function useLazyList() {
    let images1 = document.querySelectorAll('.list_bottom > li > img')
    new LazyLoad(images1)
}
/****************  页面渲染完毕 ******************/


/****************  +++各种事件 ******************/
list_top.addEventListener('click', e => {

    /************* 分类列表 ************/
    if (e.target.className === 'cate') {
        console.log(e.target)
        // 切换类名
        for (let i = 0; i < listClass.children.length; i++) {
            listClass.children[i].classList.remove('active')
        }
        e.target.classList.add('active')


        // 修改 Info 里面的信息, 重新渲染页面的列表
        const text = e.target.innerText
        listInfo.category = text === '全部' ? '' : text
        listInfo.current = 1
        // 重新渲染
        goodsList()
    }

    /************* 筛选按钮 ************/
    if (e.target.className === 'fliter_item') {
        console.log(e.target)


        for (let i = 0; i < list_choose.children.length; i++) {
            list_choose.children[i].classList.remove('active')
        }
        e.target.classList.add('active')


        listInfo.filter = e.target.dataset.type

        goodsList()
    }

    /************* 折扣按钮 ************/
    if (e.target.className === 'sale_') {


        for (let i = 0; i < list_sale.children.length; i++) {
            list_sale.children[i].classList.remove('active')
        }
        e.target.classList.add('active')

        listInfo.saleType = e.target.dataset.sale
        listInfo.current = 1
        goodsList()
    }


    /************* 排序按钮 ************/
    if (e.target.className === 'sort_') {
        console.log(e.target)

        for (let i = 0; i < list_sort.children.length; i++) {
            list_sort.children[i].classList.remove('active')
        }
        e.target.classList.add('active')

        listInfo.sortType = e.target.dataset.type
        listInfo.sortMethod = e.target.dataset.meth
        listInfo.current = 1
        goodsList()

    }


    /************* 上下一页按钮 ************/
    if (e.target.className === 'pagerig') {
        // console.log(e.target)
        listInfo.current++
        goodsList()
    }
    if (e.target.className === 'pagelef') {
        console.log(e.target)
        listInfo.current--
        goodsList()
    }


    /************* 点击跳转的按钮 ************/
    if (e.target.className === 'goToPage') {
        let page = choose_page.value - 0
        const total = choose_page.dataset.total

        if (!page) page = 1   //如果 不是数字
        if (page < 1) page = 1
        if (page > total) page = total
        page = parseInt(page)

        listInfo.current = page
        goodsList()

    }


    /************* 点击一页显示多少条的按钮 ************/
    list_pigeSize.addEventListener('change', () => {
        listInfo.pagesize = list_pigeSize.value - 0
        listInfo.current = 1
        goodsList()
    })
})
/****************  各种事件结束 ******************/

/************* +++模糊搜索 ************/
list_search_inp.addEventListener('input', () => {
    listInfo.search = list_search_inp.value.trim()
    listInfo.current = 1
    goodsList()
})
/************* 模糊搜索结束 ************/


/************* +++跳转详情页 ************/
list_bottom.addEventListener('click', e => {
    if (e.target.nodeName === 'LI') {

        const id = e.target.dataset.id
        console.log(id)
        window.sessionStorage.setItem('goodsId', id)
        window.location.href = 'detail.html'

    }


    if (e.target.nodeName === 'BUTTON') {
        const goodsId = e.target.dataset.id 
        // console.log(goodsId)
        // console.log(e.target)
        addCart(goodsId)
    }
})
/************* 跳转详情页结束 ************/

/************* 加入购物车 ************/
 function addCart(goodsId) {

    const token = window.localStorage.getItem('token')
    const id = window.localStorage.getItem('id')
    // console.log(token, id)

    if (!id) {
        const res = window.confirm('您还未登录,点击确定返回登录页,点击取消留在此页面')
        if (res) {
            window.location.href = 'login.html'
            return
        }
        return  // 点击确定到这里, 把购物车函数断掉
    }

    // 代码来到这里. 说明有 id
   $.ajax({
        url: 'http://localhost:8888/cart/add',
        method: 'POST',
        data: { id, goodsId },
        headers: { authorization: token },
    }).then(res => {
    //    console.log(res)
        if ( res.code === 401 ) {
            const info = window.confirm('登录过期,请重新登录')
    
            if (info) {
                window.location.href = 'login.html'
                return
            }
            return
        }
        if (res.code === 1) {
            alert('加入购物车成功')
        }
    })
}
/************* 加入购物车结束 ************/

